package com.shihan.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;

/**
 * @Description
 * @Author shihan
 * @Date 2021/1/9 20:11
 * @Version 1.0
 */
public class TTLProducer {

    public static final String QUEUE_NAME_TTL = "queue.name.ttl";

    public static final String EXCHANGE_NAME_TTL = "exc.name.ttl";

    public static final String BINDING_KEY = "key.ttl";

    public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri("amqp://root:123456@192.168.66.129/%2f");

        /**
         * 将指定资源放在 try 的内部时，在 try catch 结束后，这些资源就将被释放！
         */
        try(
            Connection connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();) {

            // Queue TTL 相关的参数设置 Map
            HashMap<String, Object> queueArguments = new HashMap<>();
            // 消息队列中的消息，过期时间为 30 秒！
            queueArguments.put("x-message-ttl", 30 * 1000);
            // 如果当前消息队列没有消费者，那么 60 秒后，当前消息队列就会过期！
            queueArguments.put("x-expires", 60 * 1000);

            // 声明队列
            channel.queueDeclare(QUEUE_NAME_TTL,true,false,false,queueArguments);

            channel.exchangeDeclare(EXCHANGE_NAME_TTL, BuiltinExchangeType.DIRECT);

            channel.queueBind(QUEUE_NAME_TTL,EXCHANGE_NAME_TTL,BINDING_KEY);

            AMQP.BasicProperties basicProperties = new AMQP.BasicProperties.Builder()
                    .contentEncoding("utf-8")
                    .deliveryMode(2)    // deliveryMode = 2 表示持久化！
                    .build();
            channel.basicPublish(EXCHANGE_NAME_TTL,BINDING_KEY,basicProperties,"TTL消息！".getBytes("utf-8"));

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }

    }

}
